#include <stdio.h>
#include <stdlib.h>
#include <assert.h>

#include "thread.h"
#include "semaphore/semaphore.h"

/*Note: this test requires the preamption to be disabled*/

void * threadfunc1(void * arg){
   semaphore_t sem = *(semaphore_t *) arg;
   wait_optsemaphore(sem);

   printf("je suis le thread 1:%p\n",thread_self());
   thread_yield();

   printf("je suis encore le thread 1:%p\n",thread_self());
   thread_yield();

   printf("je suis toujours le thread 1:%p\n",thread_self());
   post_optsemaphore(sem);

   return NULL;
}

void * threadfunc2(void * arg){
   semaphore_t sem = *(semaphore_t *) arg;
   wait_optsemaphore(sem);

   printf("je suis le thread 2:%p\n",thread_self());
   post_optsemaphore(sem);

   return NULL;
}

int main(void)
{
  thread_t thread1, thread2;
  void *retval1, *retval2;
  int err;

  semaphore_t sem1 = init_optsemaphore(1);

  err = thread_create(&thread1, threadfunc1, &sem1);
  assert(!err);


  err = thread_create(&thread2, threadfunc2, &sem1);
  assert(!err);

  printf("je suis le main:%p\n",thread_self());
  thread_yield();
  printf("je suis le main:%p\n",thread_self());
  thread_yield();
  printf("je suis le main:%p\n",thread_self());

  err = thread_join(thread1, &retval1);
  assert(!err);
  err = thread_join(thread2, &retval2);
  assert(!err);

  free_optsemaphore(sem1);

  thread_exit(NULL);
  return 0;
}
